package sample.sugar;

import org.junit.Test;
import tech.mhuang.pacebox.core.sugar.Attempt;

import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Supplier;

import static org.junit.Assert.assertEquals;

public class AttemptTest {

    @Test(expected = RuntimeException.class)
    public void testAccept() {
        Consumer<Object> action = Attempt.accept(this::throwableAccept);
        action.accept("");
    }

    @Test
    public void testAcceptWithHandler() {
        //accept 调用方法,ex此处截获异常可自行决定是否抛出
        Consumer<Object> action = Attempt.accept(this::throwableAccept, ex -> System.out.println("出现异常" + ex.getMessage()));
        action.accept("21112");
        System.out.println("```");
    }

    @Test(expected = RuntimeException.class)
    public void testApply() {
        Function<Object, Object> mapper = Attempt.apply(this::throwableApply);

        mapper.apply("");
    }

    @Test
    public void testApplyWithHandler() {
        //传递参数.integer是应答参数.ex 代表异常可返回一个值.或者自行抛出异常
        Function<Object, Integer> mapper = Attempt.apply(this::throwableApply, ex -> 0);
        Integer result = mapper.apply("");
        assertEquals(0L, (long) result);
    }

    @Test(expected = RuntimeException.class)
    public void testSupply() {
        Supplier<Integer> supplier = Attempt.supply(this::throwableSupply);
        supplier.get();
    }

    @Test
    public void testSupplyWithHandler() {
        Supplier<Integer> supplier = Attempt.supply(this::throwableSupply, ex -> 0);
        assertEquals(0, supplier.get().intValue());
    }

    @Test
    public void testInvoke() {
        Integer responseData = Attempt.invoke(() -> "1", response -> Integer.parseInt(response) / 0, error -> {
            error.printStackTrace();
            return null;
        });
        System.out.println("1=" + responseData);
        responseData = Attempt.invoke(() -> "1", response -> Integer.parseInt(response) / 0);
        System.out.println("2=" + responseData);
    }

    private void throwableAccept(Object value) throws Exception {
        System.out.println(value);
        throw new Exception("throwableAccept");
    }

    private int throwableApply(Object value) throws Exception {
        throw new Exception("throwableApply");
    }

    private int throwableSupply() throws Exception {
        throw new Exception("throwableSupply");
    }
}
